package com.cskaoyan.controller;


import com.cskaoyan.bean.baseresultVO.BaseData;
import com.cskaoyan.bean.baseresultVO.BaseParam;
import com.cskaoyan.bean.baseresultVO.BaseRespVo;
import com.cskaoyan.bean.domain.Admin;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.utils.Md5Util;
import com.cskaoyan.utils.ParameterValidationUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;


/**
 * @User: Yr
 * @Date: 2021/11/29
 * @Description:
 */

@RestController
@RequestMapping("admin/admin")
public class AdminController {

    @Autowired
    AdminService adminService;


    /**
     * 查询指定adminList
     * @Description: 仅显示deleted为false的admin
     */
    @RequiresPermissions("admin:admin:list")
    @RequestMapping("list")
    public BaseRespVo list(String username, BaseParam baseParam) {
        BaseData data = adminService.list(username, baseParam);
        return BaseRespVo.ok(data);
    }

    /**
     * 删除admin
     * @Description: 逻辑删除 且不能删除id为1的管理员
     */
    @RequiresPermissions("admin:admin:delete")
    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody Admin admin) {
        if (admin.getId() == 1) return BaseRespVo.error(401, "不能删除管理员admin123!");
        adminService.delete(admin);
        return BaseRespVo.ok(null);
    }

    /**
     * 新增admin
     * @Description: 参数校验:用户名唯一, 用户名密码均不少于6位 密码采用md5加密后存入数据库
     */
    @RequiresPermissions("admin:admin:create")
    @RequestMapping("create")
    public BaseRespVo create(@RequestBody @Valid Admin admin, BindingResult bindingResult) {
        ParameterValidationUtil.paramValidation(bindingResult);
        try {
            String newPwd = Md5Util.getMd5AdDefaultSalt(admin.getPassword());
            admin.setPassword(newPwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Admin resultAdmin = adminService.create(admin);
        return BaseRespVo.ok(resultAdmin);
    }

    /**
     * 更新admin
     * @Description: 参数校验:用户名唯一, 用户名密码均不少于6位 密码采用md5加密后存入数据库
     */
    @RequiresPermissions("admin:admin:update")
    @RequestMapping("update")
    public BaseRespVo update(@RequestBody @Valid Admin admin, BindingResult bindingResult) {
        ParameterValidationUtil.paramValidation(bindingResult);
        try {
            String newPwd = Md5Util.getMd5AdDefaultSalt(admin.getPassword());
            admin.setPassword(newPwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Admin resultAdmin = adminService.update(admin);
        return BaseRespVo.ok(resultAdmin);
    }


}

